﻿define([
  'models/abmManagers/companyManager',
  'models/abmManagers/preferenceManager',
  'text!templates/abmManagers/abmBaseTmp.html',
  'text!templates/abmManagers/abmFormTmp.html',
  'text!templates/abmManagers/preference/auxiliar/entityPrefEdit.html',
  'text!templates/abmManagers/preference/auxiliar/preferenceItem.html',
], function (cmpyModel, prefModel, BaseTmp, FormTmp, UniqTmp, PrefTmp) {
    var view = Backbone.View.extend({
        el: $("#main"),
        _uId: "",
        _company: {},
        _prevSel: { moduleId: "" },
        render: function () {
            $("#mainLoading").show();
            $("div[data-rel='abm-company']").remove();
            var cmpyMod = new cmpyModel();
            var prefMod = new prefModel();
            var _this = this;
            this._uId = $.uuid();

            cmpyMod.GetCompany(this.options.companyId, function (dataCompany) {
                _this._company = dataCompany;
                prefMod.ListPrefModules(function (dataPrefModules) {
                    var baseTemplate = Handlebars.compile(BaseTmp);
                    var formTemplate = Handlebars.compile(FormTmp);
                    var uniqTemplate = Handlebars.compile(UniqTmp);

                    var dataBaseTemplate = {
                        id: _this._uId,
                        dataRel: "abm-company", // cuidado, ref en js
                        tmpClass: "company-pref-edit", // cuidado, ref en css
                        title: translate("_editCompanyPreferences")
                    };
                    var dataUniqTemplate = {
                        prefModule: dataPrefModules
                    };

                    var html = baseTemplate(dataBaseTemplate);
                    var html2 = formTemplate();
                    var html3 = uniqTemplate(dataUniqTemplate);

                    _this.$el.append(html);
                    $("div[data-id='" + _this._uId + "']").find("div.abm-content").append(html2);
                    $("div[data-id='" + _this._uId + "']").find("div.form-content").append(html3);

                    postRender(_this.$el.find("div[data-id='" + _this._uId + "']"));

                    _this.firstValues();
                    
                    _this.addHandlers();
                    $("#mainLoading").hide();
                });
            });
        },
        firstValues: function () {
            var _this = this;
            _this._prevSel = {
                moduleId: $("div[data-id='" + _this._uId + "']").find("div.pref-module-selection select").val()
            };
            
            // al cargar los valores iniciales, se puede preguntar si el TYPE es companyPref o algo asi
            var prefMod = new prefModel();
            prefMod.List(undefined, function (dataPref) {
                if (_this._company.preferences && _this._company.preferences.length > 0) {
                    for (var k = 0; k < _this._company.preferences.length ; k++) {
                        for (var i = 0; i < dataPref.length ; i++) {
                            if (dataPref[i].preferenceId == _this._company.preferences[k].preferenceId) {
                                // si no tiene valor almacenado, le agrega el default
                                if (_this._company.preferences[k].value == "" || _this._company.preferences[k].value == undefined) {
                                    _this._company.preferences[k].value = dataPref[i].defaultValue;
                                }
                                break;
                            } else if (i + 1 == dataPref.length) {
                                _this._company.preferences.push(dataPref[i]);
                            }
                        }
                    }
                }
                else {
                    for (var k = 0; k < dataPref.length ; k++) {
                        _this._company.preferences[k] = {
                            value: dataPref[k].defaultValue,
                            moduleId: dataPref[k].moduleId,
                            preferenceId: dataPref[k].preferenceId
                        }
                    }
                }
                _this.changeList(_this._prevSel);
            });
        },
        reRender: function () {
            var _this = this;

            _this.saveCurrentItems(function () {
                var slctdPrefMod = {
                    moduleId: $("div[data-id='" + _this._uId + "']").find("div.pref-module-selection select").val()
                };

                var divPrefContent = $("div[data-id='" + _this._uId + "']").find("div.pref-content").children();
                if ($(divPrefContent).length > 0) {
                    $(divPrefContent).fadeOut(100, "linear", function () {
                        _this.changeList(slctdPrefMod);
                    });
                } else
                    _this.changeList(slctdPrefMod);

            });
        },
        saveCurrentItems: function (callback) {
            var _this = this;
            var prefList = $("div[data-id='" + _this._uId + "']").find("div.pref-content input");

            // Carga datos del formulario actual en arreglo auxiliar.
            if (prefList.length > 0) {
                var auxList = [{}];
                for (var i = 0; i < prefList.length ; i++) {
                    auxList[i] = {
                        preferenceId: $(prefList[i]).attr("data-id"),
                        value: prefList[i].value,
                        moduleId: _this._prevSel.moduleId
                    }
                }
                // actualiza preferencias
                if (auxList.length > 0) {
                    if (_this._company.preferences.length == 0) {
                        _this._company.preferences = auxList;
                    } else {
                        for (var i = 0; i < auxList.length ; i++) {
                            for (var j = 0; j < _this._company.preferences.length ; j++) {
                                if (_this._company.preferences[j].preferenceId == auxList[i].preferenceId) {
                                    _this._company.preferences[j].value = auxList[i].value;
                                    break;
                                } else if (j + 1 == _this._company.preferences.length) {
                                    _this._company.preferences.push(auxList[i]);
                                }
                            }
                        }
                    }
                }
            }
            callback();
        },
        changeList: function (selectedModule) {
            var _this = this;
            var prefMod = new prefModel();

            prefMod.List(selectedModule.moduleId, function (dataPref) {
                var prefTemplate = Handlebars.compile(PrefTmp);
                // carga el valor de preferencia de la company en caso que tenga uno diferente al default
                for (var i = 0; i < dataPref.length ; i++) {
                    for (var j = 0; j < _this._company.preferences.length ; j++) {
                        if (dataPref[i].preferenceId == _this._company.preferences[j].preferenceId) {
                            dataPref[i].defaultValue = _this._company.preferences[j].value;
                            break;
                        }
                    }
                }

                var dataPrefItemTemplate = {
                    data: dataPref
                };
                var html = prefTemplate(dataPrefItemTemplate);
                
                var divPrefContent = $("div[data-id='" + _this._uId + "']").find("div.pref-content");
                $(divPrefContent).children().remove();
                $(divPrefContent).append(html);
                $(divPrefContent).children().fadeIn(100, "linear", function () {

                });
                
                _this._prevSel.moduleId = selectedModule.moduleId;
            });
        },
        save: function () {
            var _uId = this._uId;
            var _this = this;
            var cmpyMod = new cmpyModel();

            _this.saveCurrentItems(function () {
                cmpyMod.Update(_this._company, function () {
                    require(['controllers/abmManagers/companyManager'], function (Controller) {
                        (new Controller()).show();
                    });
                });
            });
        },
        cancel: function () {
            require(['controllers/abmManagers/companyManager'], function (Controller) {
                (new Controller()).show();
            });
        },
        addHandlers: function () {
            $("div[data-id='" + this._uId + "']").find("form").on("submit", $.proxy(function () {
                this.save();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.submit button.btn-cancel").on("click", $.proxy(function () {
                this.cancel();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.pref-module-selection select").on("change", $.proxy(function () {
                this.reRender();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.abm-top-options a.btn-close").on("click", this.cancel);
        }
    });
    return view;
});